'- 
'-  teste1_0108231230_msx2_screen07_conv.txt
'- 010808 - primeira tentativa no firstbasic-dos
'- input= 512x424 

finp$="picture.jpg"
scrmod7=0 '- scrmod7=0 is screen5, scrmod7=1 is screen7
lacmod=0 '- lacmod=0 is 212, lacmod=1 is 424
lacknd=0 '- lacknd=0 is sequential, lacknd=1 is laced
extnd=0 '- extnd=0 is 192, extnd=1 is 212

scrmod7=(int(scrmod7))mod 2
lacmod=(int(lacmod))mod 2
if lacmod=0 then:lacknd=0:end if

if scrmod7=0 then: suf$="5": else: suf$="7":end if
if lacmod=0 then: suf$+="s": else: suf$+="d":end if
if lacknd=0 then: suf$+="n": else: suf$+="l":end if

dim npaletr[16],npaletg[16],npaletb[16],grpltlev[16]

tmfl$="_tmpr01.gif"
shell("convert "+finp$+" -colors 16 "+tmfl$)

open tmfl$ for input as #1
for i=1 to 13:n=readbyte(1):next
for i=0 to 15
  n=readbyte(1):npaletr[i]=int((int(n/32))*(255/7))
  n=readbyte(1):npaletg[i]=int((int(n/32))*(255/7))
  n=readbyte(1):npaletb[i]=int((int(n/32))*(255/7))
  next
close #1
shell ("rm "+tmfl$)

for i=0 to 15:grpltlev[i]=int(((npaletr[i]*30)+(npaletg[i]*59)+(npaletb[i]*11))/100): next
for i=0 to 14
for j=i+1 to 15
if grpltlev[i]>grpltlev[j] then
  tmprq=grpltlev[i]:grpltlev[i]=grpltlev[j]:grpltlev[j]=tmprq
  tmprq=npaletr[i]:npaletr[i]=npaletr[j]:npaletr[j]=tmprq
  tmprq=npaletg[i]:npaletg[i]=npaletg[j]:npaletg[j]=tmprq
  tmprq=npaletb[i]:npaletb[i]=npaletb[j]:npaletb[j]=tmprq
end if
next:next

f2$=finp$+"."+suf$ '-".a07"
'f3$=finp$+".b07"
xed=256*(scrmod7+1)  'xed=512
yed=212*(lacmod+1)   'yed=424

if extnd=0 then
  yed=192*(lacmod+1)   'yed=384
  end if

setdisplay(xed,yed,32,1):paper(8^8-1):ink(0):pen(0):cls
loadimage(finp$,1):pasteicon(0,0,1)


open f2$ for output as #2

for yp2=0 to lacknd
 for yp1=0 to yed-1 step (lacknd+1)
  yp=yp1+yp2
  setcaption("line "+str$(yp)+"/423")
  for x=0 to xed-1
    c=point(x,yp)
    ri=bitwiseand((int(c/65536)),0xFF)
    gi=bitwiseand((int(c/256  )),0xFF)
    bi=bitwiseand(c,0xFF)
    
    dbuf=999:didv=0
    for i=0 to 15
      rdist=abs(npaletr[i]-ri):gdist=abs(npaletg[i]-gi):bdist=abs(npaletb[i]-bi)
      rgbdist=sqr((rdist^2)+(gdist^2)+(bdist^2))
      if rgbdist<=dbuf then:
        dbuf=rgbdist
        didv=i
        end if
      next
    
    if (x mod 2)<1 then:
      ci=(didv*16)
    else
      ci=bitwiseor(ci,didv)
      writebyte(2,ci)

      end if    
    next:next:next

close #2

plt$=""
for i=0 to 15
  plt$=plt$+str$(int(npaletr[i]/32))+","+str$(int(npaletg[i]/32))+","+str$(int(npaletb[i]/32)) 
  if i<15 then:plt$=plt$+",":end if
  next

setcaption("done")
